package cn.yitun.chat.yitunservermanagecore.general.manage.generator.service.impl;

import cn.yitun.chat.yituncommonmessage.ExceptionEnum;
import cn.yitun.chat.yituncommonmessage.YitunException;
import cn.yitun.chat.yituncommonutil.YitunMapUtil;
import cn.yitun.chat.yitunservercommonlib.dataentity.po.common.GeneratorInfo;
import cn.yitun.chat.yitunserverimbase.dao.common.GeneratorMapper;
import cn.yitun.chat.yitunservermanagecore.general.manage.generator.service.GeneratorService;
import cn.yitun.chat.yitunservermanagecore.general.manage.generator.utils.GenUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.zip.ZipOutputStream;


@Service
public class GeneratorServiceImpl implements GeneratorService {
	@Autowired
	private GeneratorMapper generatorMapper;

	@Override
	public List<Map<String, Object>> list() {
		List<Map<String, Object>> list = generatorMapper.list();
		return list;
	}

	@Override
	public List<Map<String, Object>> page(Map<String, Object> params) {
		List<Map<String, Object>> list = generatorMapper.page(params);
		return list;
	}

	@Override
	public int count(Map<String, Object> params) {
		return generatorMapper.count(params);
	}

	@Override
	public byte[] generatorCode(List<String> tableNames) {
		ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
		ZipOutputStream zip = new ZipOutputStream(outputStream);
		for(String tableName : tableNames){
			//查询表信息
			Map<String, String> table = generatorMapper.get(tableName);
			//查询列信息
			List<Map<String, String>> columns = generatorMapper.listColumns(tableName);
			//生成代码
			GenUtils.generatorCode(getGeneParam("0") ,table, columns, zip);
		}
        if (zip != null) {
            try {
                zip.close();
            } catch (IOException var2) {
                throw new YitunException(ExceptionEnum.BUSY_SERVER);
            }
        }
		return outputStream.toByteArray();
	}

	@Override
	public GeneratorInfo getGeneParam(String id) {
		return generatorMapper.getGeneParam(id);
	}

	@Transactional
	@Override
	public void updateGeneParam(GeneratorInfo generatorInfo) {
		generatorMapper.updateGeneParam(YitunMapUtil.java2Map(generatorInfo , false));
	}
}
